package westh.ilib.struts.action.getHotResources;

import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.mule.extras.client.MuleClient;
import org.mule.impl.MuleMessage;
import org.mule.umo.UMOMessage;

//import westh.ilib.bean.zhaojie.AcademicMeeting;

/*import westh.ilib.struts.action.zhaojie.JSONArray;
import westh.ilib.struts.action.zhaojie.JSONObject;
import westh.util.YyAction;*/

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.util.ArrayList;
import java.util.List;

import westh.ilib.bean.croDomainSearch.Resource;
import westh.ilib.service.HotResourceService;
import westh.ilib.service.UserService;
import westh.ilib.util.PageInfo;

/**
 * @author yanfei
 * modifier gaoyang
 */

public class GetHotResourceAction extends Action {
	private final static Log log = LogFactory.getLog(GetHotResourceAction.class);
	
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
				westh.log.YyLog.addFootprint(request, "GetHotResourceAction");
				DynaActionForm f = (DynaActionForm) form;
				//String inputStr = f.getString("inputStr");
				
				/* get parameters from html */
				String dateStart = request.getParameter("Start");
				String dateEnd = request.getParameter("End");
				String personalize = request.getParameter("personalize");
				String resourceCount = request.getParameter("resourceCount");
		
				
				log.debug("dateStart = " + dateStart);
				log.debug("dateEnd = " + dateEnd);
				log.debug("personalize = " + personalize);
				log.debug("resourceCount = " + resourceCount);
				
				// dispatch page related begin
		        String strPageNo = (String)request.getParameter("pageNo");
		        
		        String strPageSize = (String)request.getParameter("pageSize");
		        
		        // dispatch page related end
		        
		        log.debug("strPagesize="+strPageSize);
				
				//String userId=request.getRemoteUser();    // get user id
				String userId = "???";    // user id
				String Code = "0600";     // the code of html parameters parsed result
				String Msg = "???";       // the message of html parameters parsed result
				
				/* parse html parameters */
				if (userId.equals(null) || userId.length() == 0 || userId.length() > 25  // user id format is a string not longer than 25 chars
						// personalize is either 0 or 1
						|| !personalize.matches("[0-1]{1}")
						// resource count is a integer
						|| !resourceCount.matches("[0-9]+"))
				{
					Code = "0601";        // parameters parsed error (format error)
				} else if (userId.equals("")) {
					Code = "0602";        // user does not exist 
				} else {
					String[] sa = dateStart.split("[-]");
					String[] ea = dateEnd.split("[-]");
					String s = "";
					String e = "";
					for (int i = 0; i < 3; i++) {
						s += sa[i];
						e += ea[i];
					}
					int si = Integer.parseInt(s);
					int ei = Integer.parseInt(e);
					if (si > ei) {
						Code = "0603";    // paramemers logistical error
					}
				}
				log.debug("parameter resolving result = " + Code);
				
				/* call functions from HotResourceService if html parameters parsed successful */
				if (Code.equals("0600")) {
					HotResourceService HRS = new HotResourceService();
					String resIdList = HRS.getHotResIdListByDate(dateStart, dateEnd);    // get hot resource id list by date
					JSONObject resIdListJSON = JSONObject.fromObject(resIdList);
					String retCode = resIdListJSON.getString("retCode");    // return code
					String retMsg = resIdListJSON.getString("retMsg");      // return result message
					
					/* hot resource id list is not empty if return code equals 3501 */
					if (retCode.equals("3501")) {
						log.debug("get hot resource id list by date SUCCESS!");
						
						String resList = "{\"retCode\":\"3501\",\"retMsg\":\"--\",\"rscList\":[]}";                   // hot resource information list
						
						if (personalize.equals("1")) {           // personalize
							UserService US = new UserService();
							//String userDomain = US.getUserDomain(userId);
							log.debug("get user domain knowledge SUCCESS!");
							//log.debug(userDomain);
//							resList = HRS.getHotResByPersonalized(resIdList, userDomain, resourceCount);       // get hot resource information list by user domain knowledge
							resList = HRS.getHotResByPersonalized(resIdList, "[]", resourceCount);
//							resList = HRS.testPersonalized(resourceCount);
							log.debug("get hot resource information by user domain knowledge SUCCESS!");
						} else if (personalize.equals("0")) {    // not personalize
							String refinedIdList = HRS.refineHotResIdListByCount(resIdList, resourceCount);    // refine hot resource id list by count
							log.debug("refine hot resource id list by count SUCCESS!");
							
							//JSONObject tempJSON = JSONObject.fromObject(refinedIdList);
							//JSONArray tempJSONArray = tempJSON.getJSONArray("resultArray");
							//for (int i = 0; i < tempJSONArray.size(); i++) {
							//	log.debug(tempJSONArray.get(i).toString());
							//}
							
							resList = HRS.getHotResByIdList(refinedIdList);    // get hot resource information list by their id list
							log.debug("get hot resource information by their id list SUCCESS");
							
//							//log.debug(resList);
//							JSONObject tempJSON = JSONObject.fromObject(resList);
//							//log.debug(tempJSON);
//							JSONArray tempJSONArray = tempJSON.getJSONArray("rscList");
//							//log.debug(tempJSONArray);
//							for (int i = 0; i < tempJSONArray.size(); i++) {
//								log.debug(tempJSONArray.get(i).toString());
//							}
						}
						log.debug(resList);
						
						/* set attribute for JSP */
//						resList = "{\"rscList\":[{\"rscTitle\":\"Artificial Intelligence\",\"rscType\":\"1\",\"rscPublishDate\":\"2010-01-01\",\"rscAuthor\":\"AI\",\"rscField\":\"1\",\"visitCount\":\"3\"}," +
//								"{\"rscTitle\":\"MultiMedia\",\"rscType\":\"2\",\"rscPublishDate\":\"2010-02-01\",\"rscAuthor\":\"MM\",\"rscField\":\"2\",\"visitCount\":\"2\"}," +
//								"{\"rscTitle\":\"Software Engineering\",\"rscType\":\"3\",\"rscPublishDate\":\"2010-03-01\",\"rscAuthor\":\"SE\",\"rscField\":\"3\",\"visitCount\":\"1\"}]}";
						JSONObject rscListJSON = JSONObject.fromObject(resList);
						JSONArray rscListJSONArray = rscListJSON.getJSONArray("rscList");
						List<Resource> rscList = new LinkedList<Resource>();
						for (int i = 0; i < rscListJSONArray.size(); i++) {
							JSONObject infoJSON = JSONObject.fromObject(rscListJSONArray.get(i));
//							String rscId = infoJSON.getString("rscId");
//							String rscTitle = infoJSON.getString("rscTitle");
//							String rscType = infoJSON.getString("rscType");
//							String rscPublishDate = infoJSON.getString("rscPublishDate");
//							String rscAuthor = infoJSON.getString("rscAuthor");
//							String rscField = infoJSON.getString("rscField");
//							int visitCount = infoJSON.getInt("visitCount");
//							List<String> rscInfo = new LinkedList<String>();
//							//rscInfo.add(infoJSON.getString("rscId"));
//							rscInfo.add(infoJSON.getString("rscTitle"));
//							rscInfo.add(infoJSON.getString("rscType"));
//							rscInfo.add(infoJSON.getString("rscPublishDate"));
//							rscInfo.add(infoJSON.getString("rscAuthor"));
//							rscInfo.add(infoJSON.getString("rscField"));
//							rscInfo.add(Integer.toString(infoJSON.getInt("visitCount")));
							Resource rscInfo = new Resource();
							if(infoJSON.getString("rscTitle").length()>40){
								rscInfo.setRscTitle(infoJSON.getString("rscTitle").substring(0,40)+"...");
							}else {
								rscInfo.setRscTitle(infoJSON.getString("rscTitle"));
							}
							
							rscInfo.setRscId(infoJSON.getString("rscId"));
							if (infoJSON.getString("rscType").equals("")) {
								rscInfo.setRscType(0);
							} else {
								rscInfo.setRscType(Integer.parseInt(infoJSON.getString("rscType")));
							}
							rscInfo.setRscPublishDate(infoJSON.getString("rscPublishDate"));
							if (infoJSON.getString("rscField").equals("")) {
								rscInfo.setRscField(0);
							} else {
								rscInfo.setRscField(Integer.parseInt(infoJSON.getString("rscField")));
							}
							
							rscList.add(rscInfo);
							log.debug("in action listSize =" + rscList.toString());
						}
						//request.setAttribute("list", rscList);
						request.setAttribute("resourceCount",resourceCount);
						/**dispatch page related 
						 * begin*/
						PageInfo pageInfo = new PageInfo();
						int iPageNo = pageInfo.getPageNoFromJSP(strPageNo);
						int iPageSize = pageInfo.getPageSizeFromJSP(strPageSize);
						log.debug("iPageSize = " + iPageSize);
						
						int num=iPageSize*(iPageNo-1);
			            request.setAttribute("num",num);
						
			            pageInfo.setMaxCount(rscList.size());
			            pageInfo.setPageNO(iPageNo);
			            pageInfo.setPageSize(iPageSize);
			            
			            List outputList=null;
			            
			            int endCount=pageInfo.getMaxCount();
			            
			            if(endCount>iPageSize*iPageNo)
			            {
			            	endCount=iPageSize*iPageNo;
			            	outputList=rscList.subList(iPageSize * (iPageNo - 1), endCount);
			            }
			            else if(endCount<iPageSize*iPageNo&&endCount>iPageSize * (iPageNo - 1))
			            {
			            	outputList=rscList.subList(iPageSize * (iPageNo - 1), endCount);
			            }
			            else if(endCount==iPageSize*iPageNo)
			            {
			            	endCount=iPageSize*iPageNo;
			            	outputList=rscList.subList(iPageSize * (iPageNo - 1), endCount);
			            }
			            else
			            {
			            	iPageNo=1;
			            	pageInfo.setPageNO(iPageNo);
			            	if(endCount>iPageSize*iPageNo)
			            		endCount=iPageSize*iPageNo;
			            	outputList=rscList.subList(iPageSize * (iPageNo - 1), endCount);
			            }
			            	
			            //List outputList=list.subList(iPageSize * (iPageNo - 1), endCount);

			            pageInfo.setPageList(outputList);

			            request.setAttribute("pageInfo", pageInfo);
			            request.setAttribute("pageNo", strPageNo);
			            request.setAttribute("pageSize", strPageSize);
						request.setAttribute("Start", dateStart);
						request.setAttribute("End", dateEnd);
						request.setAttribute("personalize", personalize);
						request.setAttribute("resourceCount", resourceCount);
						/**dispatch page related 
						 * end*/
						
					} else if (retCode.equals("3502")) {         // hot resource id list is empty
						log.debug(retMsg);
						request.setAttribute("info", retMsg);
						return mapping.findForward("fail");
					} else if (retCode.equals("3503")) {         // service error
						log.debug(retMsg);
						request.setAttribute("info", retMsg);
						return mapping.findForward("fail");
					}
				} else if (Code.equals("0601")) {                // parameters parsed error
					Msg = "参数解析错误！";
					log.debug(Msg);
					request.setAttribute("info", Msg);
					return mapping.findForward("fail");
				} else if (Code.equals("0602")) {                // user does not exist
					Msg = "用户不存在！";
					log.debug(Msg);
					request.setAttribute("info", Msg);
					return mapping.findForward("fail");
				} else if (Code.equals("0603")) {                // paramemers logistical error
					Msg = "时间逻辑错误！";
					log.debug(Msg);
					request.setAttribute("info", Msg);
					return mapping.findForward("fail");
				}
				
				return mapping.findForward("succ");
//				JSONObject inJson = new JSONObject();    //封装传入后台数据使用
//				JSONObject inStr = new JSONObject();     //封装接收前台传入数据使用
//				
//				inStr.put("queryDateStart", dateStart);
//				inStr.put("queryDateEnd", dateEnd);
//				inStr.put("userId", "yanfei");
//				inStr.put("isPersonalized", personalize);
//				
//				String methodName = "getHotResource";
//				inJson.put("methodName", methodName);
//				inJson.put("jsonStr", inStr);
//				
//				String inputStr=inJson.toString();
//				log.debug("inputStr = " + inputStr);
//				
//				/**************get jSon information start***************************/
//				String outString = "";
//				try {
//					MuleClient client = new MuleClient();
//					//call WebService
//					UMOMessage umo = client.send("axis:http://166.111.134.22:5181/Test/yyiLibTest?method=rulesControl", inputStr, null);
//					outString = (String)umo.getPayload();
//				} catch (Exception e) {
//					throw new RuntimeException(e);
//				}
//				/**************get jSon information end***************************/
//				
//				String retCode="";      //返回代码
//				String retMsg="";       //返回结果信息
//				String returnStr="";    //跳转信息
//				
//				/****************解析输出jSon串   start*********************/
//				JSONObject jsonOut= JSONObject.fromObject(outString);
//				retCode = jsonOut.getString("retCode");
//				if (retCode.equals("0600")) {
//					String result = jsonOut.getString("result");
//					JSONArray resultArry = JSONArray.fromObject(result);
//					Resource  resource = new Resource();
//					List<Resource> list = new ArrayList<Resource>();
//					for (int i=0;i<resultArry.size();i++) {
//						resource = new Resource();
//						JSONObject jsonOut2 = JSONObject.fromObject(resultArry.get(i));
//						resource.setResourceId(jsonOut2.getString("resourceId"));
//						resource.setResourceTitle(jsonOut2.getString("resourceTitle"));
//						resource.setResourcePublishDate(jsonOut2.getString("resourcePublishDate"));
//						resource.setResourceFirstAuthor(jsonOut2.getString("resourceAuthor"));
//						resource.setResourceType(jsonOut2.getString("resourceType"));
//						resource.setField(jsonOut2.getString("field"));
//						list.add(resource);
//					}
//					returnStr = "succ";
//				} else if (retCode.equals("0601")) {
//					retMsg = jsonOut.getString("retMsg");
//					request.setAttribute("info", retMsg);
//					returnStr = "fail";
//				} else if (retCode.equals("0602")) {
//					retMsg = jsonOut.getString("retMsg");
//					request.setAttribute("info", retMsg);
//					returnStr = "fail";
//				} else if (retCode.equals("0603")) {
//					retMsg = jsonOut.getString("retMsg");
//					request.setAttribute("info", retMsg);
//					returnStr = "fail";
//				}
//				
//				return mapping.findForward(returnStr);
//				/****************解析输出jSon串   end*********************/
				
				/*String dateStart=f.getString("Start");
				String dateEnd=f.getString("End");
				String personalize=f.getString("personalize");
				String resourceCount=f.getString("resourceCount");*/
				
				/*JSONObject resultObject = new JSONObject();
				resultObject.put("queryDateStart", dateStart);
				resultObject.put("queryDateEnd", dateEnd);
				resultObject.put("userId", "yanfei");
				resultObject.put("isPersonalized", personalize);
				String inputStr = resultObject.toString();*/
				
				//String inputStr="{\"queryDateStart\":\""+ dateBegin +"\",\"queryDateEnd\":\""+dateEnd +"\",\"userId\":\"yanfei\",\"isPersonal\":\""+personalize+"\"}";
				//System.out.println(inputStr);
				//log.debug(inputStr);
				//jSon-String
				//String outString = "";
/*				*//**************get jSon information start***************************//*		
				try {
					MuleClient client = new MuleClient();
					//call WebService
					UMOMessage umo = client.send("axis:http://166.111.134.22:5181/Test/yyiLibTest?method=getHotResource", inputStr, null);
					outString = (String)umo.getPayload();
		
				
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				*//**************get jSon information end***************************//*
				
				String retCode=""; //返回代码
				String retMsg="";//返回结果信息
				String returnStr="";//跳转信息
				*//****************解析输出jSon串   start*********************//*
				JSONObject jsonOut= JSONObject.fromObject(outString);
				retCode = jsonOut.getString("retCode");
				if (retCode.equals("0600")) {

					String result = jsonOut.getString("result");
					JSONArray resultArry = JSONArray.fromObject(result);
					log.info("JSONArray="+resultArry.size());
					System.out.println("JSONArray="+resultArry.size());
					//解析数组
					Resource  resource = new Resource();
					List list = new ArrayList();
					for(int i=0;i<resultArry.size();i++){
						resource = new Resource();
						JSONObject jsonOut2 = JSONObject.fromObject(resultArry.get(i));
						resource.setResourceID(jsonOut2.getString("resourceId"));
						resource.setResourceTitle(jsonOut2.getString("resourceTitle"));
						resource.setResourcePublishDate(jsonOut2.getString("resourcePublishDate"));
						resource.setResourceType(jsonOut2.getString("resourceType"));
						resource.setResourceAuthor(jsonOut2.getString("resourceAuthor"));
						resource.setField(jsonOut2.getString("field"));
						list.add(resource);

					}
					*//****************解析输出jSon串   end*********************//*
					request.setAttribute("list", list);
					returnStr = "succ";

				}
				if (retCode.equals("0601")) {
					retMsg = jsonOut.getString("retMsg");
					request.setAttribute("info", retMsg);
					returnStr = "fail";
				}
				if (retCode.equals("0602")) {
					retMsg = jsonOut.getString("retMsg");
					request.setAttribute("info", retMsg);
					returnStr = "fail";
				}
				
				if (retCode.equals("0603")) {
					retMsg = jsonOut.getString("retMsg");
					request.setAttribute("info", retMsg);
					returnStr = "fail";
				}
				
				return mapping.findForward(returnStr);*/
				//return mapping.findForward("succ");
	}
	
//	String getHotResource (String input) {
//		JSONObject in = JSONObject.fromObject(input);
//		String output = "";
//		String queryDateStart = in.getString("queryDateStart");
//		String queryDateEnd = in.getString("queryDateEnd");
//		String userId = in.getString("userId");
//		String isPersonalized = in.getString("isPersonalized");
//		if (!queryDateStart.matches("[0-9]{4}[-][0-9]{2}[-][0-9]{2}")
//				|| !queryDateEnd.matches("[0-9]{4}[-][0-9]{2}[-][0-9]{2}")
//				|| userId.equals(null) || userId.length() == 0 || userId.length() > 25
//				|| !isPersonalized.matches("[0-1]{1}")) {
//			return ("0601");
//		} else if (userId == "???") {
//			return ("0602");
//		} else {
//			String[] sa = queryDateStart.split("[-]");
//			String[] ea = queryDateEnd.split("[-]");
//			String s = "", e = "";
//			for (int i = 0; i < 3; i++) {
//				s += sa[i];
//				e += ea[i];
//			}
//			int si = Integer.parseInt(s);
//			int ei = Integer.parseInt(e);
//			if (si > ei) {
//				return ("0603");
//			}
//		}
//		return output;
//	}
}
